using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BLToolkit.Data;
using DevComponents.DotNetBar;
using DevComponents.DotNetBar.Controls;
using Platform.Model;

namespace PlatformManagement
{
    public partial class SupplierForm : DevComponents.DotNetBar.Metro.MetroForm
    {
        public bool _currentRow = false;
        public SupplierForm()
        {
            InitializeComponent();
            this.grvSupplier.AutoGenerateColumns = false;
        }

        protected override void OnActivated(EventArgs e)
        {
           
            base.OnActivated(e); this.WindowState = FormWindowState.Maximized;

        }
        protected override void OnShown(EventArgs e)
        {
            var source = new BindingSource { DataSource = WorkContext.Current.Suppliers.ToList() };
            grvSupplier.DataSource = source;
            base.OnShown(e);
        }

        public List<Supplier> LocDanhSach(List<Supplier> list, int MarketID)
        {
            var ListSupByMarketId = Supplier.Objects.Where(p => p.MarketId == MarketID).ToList();

            var mancc = new HashSet<String>(ListSupByMarketId.Select(p => p.SupNo));
            var tenncc = new HashSet<String>(ListSupByMarketId.Select(p => p.FirstName + "  " + p.LastName));

            var kq =
                list.Any(p => mancc.Contains(p.SupNo) || tenncc.Contains(p.FirstName + "  " + p.LastName));
            if (kq)
            {
                var message = "There are some existing suppliers with same Supp_No or SuppName.\r\n" +
                              "Program will exclude the duplicate suppliers.\r\nDo you want to continue?";
                var msgResult = MessageBox.Show(message, "Warning !!!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (msgResult == DialogResult.No)
                    return new List<Supplier>();
            }
            var DS =
                list.Where(
                    p => !mancc.Contains(p.SupNo) && !tenncc.Contains(p.FirstName + "  " + p.LastName)).ToList();
            return DS;
        }

        private void grvSupplier_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (grvSupplier.IsCurrentRowDirty && e.RowIndex > 0&& e.ColumnIndex !=0)
            {
                var currentRow = grvSupplier.CurrentRow;

                var cellfive = currentRow.Cells[5].Value;
                var cellone = currentRow.Cells[1].Value;
                var celltwo = currentRow.Cells[2].Value;
                var cellthree = currentRow.Cells[3].Value;
                var cellsix = currentRow.Cells[6].Value;
                var cellfour = currentRow.Cells[4].Value;


                if (cellfive == null || !cellfive.ToString().StartsWith("0") || cellfive.ToString().Length > 11 || cellfive.ToString().Length < 9)
                {
                    MessageBox.Show("Tel number length must be in range 10...11", "Error", MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                    e.Cancel = true;
                }

                if (cellone == null || celltwo == null || cellthree == null || cellfour == null || cellsix == null ||
                    String.IsNullOrEmpty(celltwo.ToString()) || String.IsNullOrEmpty(cellthree.ToString()) ||
                    String.IsNullOrEmpty(cellsix.ToString())
                    || String.IsNullOrEmpty(cellfour.ToString()))
                {
                    MessageBox.Show("You have to enter value for all cells", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Cancel = true;
                }

                _currentRow = true;
            }
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            try
            {
                var result = grvSupplier.Rows.Cast<DataGridViewRow>()
                                                  .Where(p => p.Cells[1].Value != null && p.Cells[0].Value != null && Convert.ToBoolean(p.Cells[0].Value))
                                   .Select(p => p.DataBoundItem as Supplier)
                                   .ToList();
                if (result.Count == 0)
                {
                    MessageBox.Show("You must be check a value", "Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                var dlg = new MarketSelectorForm();
                if (dlg.ShowDialog() != DialogResult.OK) return;
                var Suppliers = LocDanhSach(result, dlg.MarketId);
                var bansao = Suppliers.Select(p => new Supplier()
                {
                    FirstName = p.FirstName,
                    LastName = p.LastName,
                    LastUpdated = p.LastUpdated,
                    Address = p.Address,
                    SupNo = p.SupNo,
                    Tel = p.Tel,
                    MarketId = p.MarketId
                }
                    ).ToList();
                foreach (var supplier in bansao)
                {
                    Supplier.Objects.Insert(supplier);  
                }
                MessageBox.Show("All selected suppliers is copied successful", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void grvSupplier_RowValidated(object sender, DataGridViewCellEventArgs e)
        {
            if (_currentRow)
            {
                try
                {
                    var currentRow = grvSupplier.Rows[e.RowIndex];
                    var supp = currentRow.DataBoundItem as Supplier;
                    supp.LastUpdated = DateTime.Now;
                    supp.MarketId = WorkSession.Current.Market.ID;

                    int id = WorkContext.Current.Suppliers.AddOrUpdate(supp);

                    currentRow.Cells[1].Value = id;
                    grvSupplier.CancelEdit();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            var SelectedRows = grvSupplier.Rows.Cast<DataGridViewRow>()
                                              .Where(p => p.Cells[1].Value != null && p.Cells[0].Value != null && Convert.ToBoolean(p.Cells[0].Value)).ToList();
            if (SelectedRows.Count==0)
            {
                MessageBox.Show("You must be selected a value","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }
            string message = "All selected Suppliers and related data will be deleted forever. Are you sure?";
            DialogResult dlg = MessageBox.Show(message, "Warming", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
            if (dlg == DialogResult.Yes)
            {
                for (int i = SelectedRows.Count - 1; i >= 0; i--)
                {
                    var supp = SelectedRows[i].DataBoundItem as Supplier;
                    // Goi ham xoa nha cung cap & xoa dong duoc chon
                    grvSupplier.Rows.Remove(SelectedRows[i]);
                    WorkContext.Current.Suppliers.Delete(supp);
                }
            }
        }

        private void btnFirstname_Click(object sender, EventArgs e)
        {
            grvSupplier.DataSource = new BindingSource() {DataSource = WorkContext.Current.Suppliers.SortByFirstName()};
        }

        private void btnLastName_Click(object sender, EventArgs e)
        {
            grvSupplier.DataSource = new BindingSource() {DataSource = WorkContext.Current.Suppliers.SortByLastName()};
        }
    }
}